package com.lagou.listener;

import com.lagou.entity.Order;
import com.lagou.entity.Stock;
import com.lagou.service.OrderService;
import com.lagou.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * @author 13771
 * @date 2021/1/15 16:55
 * @description  监听redis过期key,并获取过期key进行处理
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StockService stockService;

    @Autowired
    StringRedisTemplate redisTemplate;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expireKey = message.toString();
        if (expireKey.startsWith("order:")){
            Integer orderId = Integer.valueOf(expireKey.replace("order:",""));
            Order order = orderService.findById(orderId);
            order.setStatus(2);  //设置订单状态为超时
            orderService.saveOrUpdate(order);

            System.out.println(orderId +  "号订单失效，库存还原+1");
            Stock stock = stockService.findById(order.getStockId());
            stock.setNum(stock.getNum()+1);
            stockService.saveOrUpdate(stock);

            //redis中的库存数量+1
            redisTemplate.opsForValue().increment("num");

        }
    }

}
